package com.yang.spring.core.bean.definition.builder;

import com.yang.spring.core.annotations.Autowired;
import com.yang.spring.core.annotations.Resource;
import com.yang.spring.core.annotations.Service;
import com.yang.spring.core.bean.definition.BeanDefinition;
import com.yang.spring.core.bean.enums.BeanTypeEnum;
import com.yang.spring.core.utils.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ServiceBeanDefinitionBuilder extends AbstractBeanDefinitionBuilder {

    @Override
    protected void richBeanDefinitionByAnnotation(BeanDefinition beanDefinition, Class clazz) {
        beanDefinition.setBeanType(BeanTypeEnum.SERVICE);
        Service service = (Service) clazz.getAnnotation(Service.class);
        if (StringUtils.isNotEmpty(service.value())) {
            beanDefinition.setBeanName(service.value());
        }
    }

    @Override
    protected void richDependencyBeanDefinitionByAnnotation(BeanDefinition dependencyBeanDefinition,
                                                            BeanDefinition beanDefinition, Method method) {
    }

    @Override
    protected void richDependencyBeanDefinitionByAnnotation(BeanDefinition dependencyBeanDefinition,
                                                            BeanDefinition beanDefinition, Field field) {
        Autowired autowiredAnnotation = field.getAnnotation(Autowired.class);
        Resource resourceAnnotation = field.getAnnotation(Resource.class);
        if (autowiredAnnotation != null) {
            if (StringUtils.isNotEmpty(autowiredAnnotation.value())) {
                dependencyBeanDefinition.setBeanName(autowiredAnnotation.value());
            }
        } else if (resourceAnnotation != null) {
            if (StringUtils.isNotEmpty(resourceAnnotation.value())) {
                dependencyBeanDefinition.setBeanName(resourceAnnotation.value());
            }
        }
    }
}
